package com.dhruvtaara.beta.controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dhruvtaara.beta.action.RegisterAction;
import com.dhruvtaara.beta.model.viewmodel.ActionStatus;
import com.dhruvtaara.beta.model.viewmodel.UserRegister;
import com.dhruvtaara.beta.toolset.AppLog;
import com.dhruvtaara.beta.toolset.DefaultEncryption;
import com.google.gson.*;

public class RegisterServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4823893926832456849L;
	
	/**
	 * 
	 */
	private static final AppLog logger = new AppLog(
			DefaultEncryption.class.getName());

	/**
	 * returns the view
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		ServletContext context = getServletContext();
		RequestDispatcher dispatcher = context
				.getRequestDispatcher("/view/register.jsp");
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			logger.Error(e.toString());
		} catch (IOException e) {
			logger.Error(e.toString());
		}
	}

	/**
	 * process the register form post
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) {

		UserRegister user = new UserRegister();
		RegisterAction register = new RegisterAction();
		ActionStatus status = new ActionStatus();

		String emailId = request.getParameter("emailField");

		boolean isRegistered = register.isAlreadyRegistered(emailId);

		Gson gson = new Gson();

		response.setContentType("application/json");

		if (isRegistered) {
			try {
				status.setAlreadyExists(true);
				PrintWriter writer = response.getWriter();
				writer.print(gson.toJson(status));
			} catch (IOException e) {
				logger.Error(e.toString());
			}

		} else {
			user.setFirstName(request.getParameter("firstNameField"));
			user.setLastName(request.getParameter("lastNameField"));
			user.setLine1(request.getParameter("addressLine1Field"));
			user.setCity(request.getParameter("cityField"));
			user.setEmailAddress(emailId);
			user.setPhoneNumber(request.getParameter("phoneNumberField"));
			user.setPassword(request.getParameter("password2Field"));
			register.save(user);

			try {
				status.setSuccessful(true);

				PrintWriter writer = response.getWriter();
				writer.print(gson.toJson(status));
			} catch (IOException e) {
				logger.Error(e.toString());
			}
		}
	}
}
